// 性能监控和优化模块
class PerformanceMonitor {
    constructor() {
        this.fps = 0;
        this.frameCount = 0;
        this.lastTime = performance.now();
        this.frameTimes = [];
        this.maxFrameTimes = 60;
        
        // 性能指标
        this.metrics = {
            fps: 0,
            avgFrameTime: 0,
            minFrameTime: Infinity,
            maxFrameTime: 0,
            objectCount: 0,
            renderTime: 0,
            updateTime: 0
        };
    }
    
    update() {
        const currentTime = performance.now();
        const frameTime = currentTime - this.lastTime;
        
        this.frameCount++;
        this.frameTimes.push(frameTime);
        
        if (this.frameTimes.length > this.maxFrameTimes) {
            this.frameTimes.shift();
        }
        
        if (currentTime - this.lastTime >= 1000) {
            this.metrics.fps = this.frameCount;
            this.metrics.avgFrameTime = this.frameTimes.reduce((a, b) => a + b, 0) / this.frameTimes.length;
            this.metrics.minFrameTime = Math.min(...this.frameTimes);
            this.metrics.maxFrameTime = Math.max(...this.frameTimes);
            
            this.frameCount = 0;
            this.lastTime = currentTime;
            
            // 性能警告
            if (this.metrics.fps < 30) {
                console.warn(`性能警告: FPS过低 (${this.metrics.fps})`);
            }
            
            if (this.metrics.avgFrameTime > 33) {
                console.warn(`性能警告: 平均帧时间过长 (${this.metrics.avgFrameTime.toFixed(2)}ms)`);
            }
        }
    }
    
    render(ctx) {
        if (!this.metrics.fps) return;
        
        ctx.save();
        ctx.fillStyle = 'rgba(0, 0, 0, 0.7)';
        ctx.fillRect(10, 10, 200, 100);
        
        ctx.fillStyle = '#ffffff';
        ctx.font = '12px Arial';
        ctx.fillText(`FPS: ${this.metrics.fps}`, 20, 30);
        ctx.fillText(`平均帧时间: ${this.metrics.avgFrameTime.toFixed(1)}ms`, 20, 50);
        ctx.fillText(`对象数量: ${this.metrics.objectCount}`, 20, 70);
        ctx.fillText(`渲染时间: ${this.metrics.renderTime.toFixed(1)}ms`, 20, 90);
        
        ctx.restore();
    }
}

// 对象池管理器
class ObjectPool {
    constructor(createFn, resetFn) {
        this.pool = [];
        this.createFn = createFn;
        this.resetFn = resetFn;
        this.activeCount = 0;
        this.totalCreated = 0;
    }
    
    get() {
        let obj;
        if (this.pool.length > 0) {
            obj = this.pool.pop();
        } else {
            obj = this.createFn();
            this.totalCreated++;
        }
        
        this.activeCount++;
        return obj;
    }
    
    release(obj) {
        if (this.resetFn) {
            this.resetFn(obj);
        }
        this.pool.push(obj);
        this.activeCount--;
    }
    
    getStats() {
        return {
            active: this.activeCount,
            pooled: this.pool.length,
            totalCreated: this.totalCreated
        };
    }
}

// 空间分区优化
class SpatialHash {
    constructor(cellSize) {
        this.cellSize = cellSize;
        this.grid = new Map();
        this.entityMap = new Map(); // 记录实体在哪个格子
    }
    
    getKey(x, y) {
        return `${Math.floor(x / this.cellSize)},${Math.floor(y / this.cellSize)}`;
    }
    
    insert(entity) {
        const key = this.getKey(entity.x, entity.y);
        
        if (!this.grid.has(key)) {
            this.grid.set(key, []);
        }
        
        this.grid.get(key).push(entity);
        this.entityMap.set(entity, key);
    }
    
    update(entity) {
        const oldKey = this.entityMap.get(entity);
        const newKey = this.getKey(entity.x, entity.y);
        
        if (oldKey !== newKey) {
            // 从旧格子移除
            if (oldKey && this.grid.has(oldKey)) {
                const oldCell = this.grid.get(oldKey);
                const index = oldCell.indexOf(entity);
                if (index > -1) {
                    oldCell.splice(index, 1);
                }
            }
            
            // 添加到新格子
            if (!this.grid.has(newKey)) {
                this.grid.set(newKey, []);
            }
            this.grid.get(newKey).push(entity);
            this.entityMap.set(entity, newKey);
        }
    }
    
    remove(entity) {
        const key = this.entityMap.get(entity);
        if (key && this.grid.has(key)) {
            const cell = this.grid.get(key);
            const index = cell.indexOf(entity);
            if (index > -1) {
                cell.splice(index, 1);
            }
        }
        this.entityMap.delete(entity);
    }
    
    getNearby(x, y, radius) {
        const nearby = [];
        const centerKey = this.getKey(x, y);
        const [centerX, centerY] = centerKey.split(',').map(Number);
        
        const range = Math.ceil(radius / this.cellSize);
        
        for (let dx = -range; dx <= range; dx++) {
            for (let dy = -range; dy <= range; dy++) {
                const key = `${centerX + dx},${centerY + dy}`;
                if (this.grid.has(key)) {
                    nearby.push(...this.grid.get(key));
                }
            }
        }
        
        return nearby;
    }
    
    clear() {
        this.grid.clear();
        this.entityMap.clear();
    }
}

// 渲染优化
class RenderOptimizer {
    constructor() {
        this.offscreenCanvas = document.createElement('canvas');
        this.offscreenCtx = this.offscreenCanvas.getContext('2d');
        this.cachedRenders = new Map();
        this.lastCameraPos = { x: 0, y: 0 };
    }
    
    // 预渲染静态内容
    preRenderBackground(width, height) {
        this.offscreenCanvas.width = width;
        this.offscreenCanvas.height = height;
        
        const ctx = this.offscreenCtx;
        ctx.fillStyle = '#000000';
        ctx.fillRect(0, 0, width, height);
        
        // 绘制网格或其他静态元素
        ctx.strokeStyle = '#333333';
        ctx.lineWidth = 1;
        
        for (let x = 0; x < width; x += 50) {
            ctx.beginPath();
            ctx.moveTo(x, 0);
            ctx.lineTo(x, height);
            ctx.stroke();
        }
        
        for (let y = 0; y < height; y += 50) {
            ctx.beginPath();
            ctx.moveTo(0, y);
            ctx.lineTo(width, y);
            ctx.stroke();
        }
    }
    
    // 渲染背景
    renderBackground(ctx, cameraX, cameraY) {
        const pattern = ctx.createPattern(this.offscreenCanvas, 'repeat');
        ctx.save();
        ctx.translate(-cameraX % 50, -cameraY % 50);
        ctx.fillStyle = pattern;
        ctx.fillRect(cameraX, cameraY, ctx.canvas.width, ctx.canvas.height);
        ctx.restore();
    }
    
    // 缓存精灵渲染
    cacheSprite(sprite, key) {
        if (this.cachedRenders.has(key)) {
            return this.cachedRenders.get(key);
        }
        
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        canvas.width = sprite.width || 32;
        canvas.height = sprite.height || 32;
        
        // 渲染精灵到缓存
        sprite.renderToCanvas(ctx);
        
        this.cachedRenders.set(key, canvas);
        return canvas;
    }
}

// 内存管理
class MemoryManager {
    constructor() {
        this.objectCounts = new Map();
        this.lastCleanup = performance.now();
        this.cleanupInterval = 5000; // 5秒清理一次
    }
    
    trackObject(type) {
        this.objectCounts.set(type, (this.objectCounts.get(type) || 0) + 1);
    }
    
    untrackObject(type) {
        this.objectCounts.set(type, Math.max(0, (this.objectCounts.get(type) || 0) - 1));
    }
    
    getStats() {
        const stats = {};
        for (const [type, count] of this.objectCounts) {
            stats[type] = count;
        }
        return stats;
    }
    
    cleanup(game) {
        const currentTime = performance.now();
        if (currentTime - this.lastCleanup < this.cleanupInterval) {
            return;
        }
        
        // 清理死亡的对象
        if (game.enemies) {
            game.enemies = game.enemies.filter(enemy => !enemy.isDead);
        }
        
        if (game.weapons && game.weapons.projectiles) {
            game.weapons.projectiles = game.weapons.projectiles.filter(proj => !proj.isDead);
        }
        
        if (game.particleSystem) {
            game.particleSystem.particles = game.particleSystem.particles.filter(particle => !particle.isDead);
        }
        
        this.lastCleanup = currentTime;
    }
}

// 全局性能监控实例
window.performanceMonitor = new PerformanceMonitor();
window.memoryManager = new MemoryManager(); 